<template>
  <!-- <el-button @click="add()">add</el-button> -->
  <!-- <el-button @click="onRemoveSelected()">remove</el-button> -->

  <AgGridVue :rowHeight="33" :headerHeight="33" v-loading="loadingElplus" @grid-ready="gridReady"
    @columnResized="onColumnResized" @click="AggridonClick" @columnMoved="onColumnMoved"
    @columnVisible="onColumnVisible" @SelectionChanged="selecetionChange" @FilterChanged="onFilterChangeds"
    @row-clicked="onRowClicked" @cellClicked="onCellClicked" :suppressClipboardPaste="true"
    style="height: calc(100% - 45px); width: 99%" :defaultColDef="{
      sortable: true, //可排序
      resizable: true, //可拖动改变列宽
      filter: true, //可过滤筛选
      editable: false, //是否可编辑
      // floatingFilter: true,
    }" class="ag-theme-alpine" :rowData="pageData.dataList"
    :columnDefs="setAggridMinwidths(props.configaggrid.column, gridOption)"
    :suppressRowClickSelection="props.configaggrid.isRowClickSelect" :suppressCopyRowsToClipboard="true"
    :suppressDragLeaveHidesColumns="true" :localeText="localeText" :isRowSelectable="isRowSelectable"
    :enableBrowserTooltips="true" :enableCellTextSelection="true" :tooltipMouseTrack="true" :tooltipShowDelay="100"
    :rowSelection="props.configaggrid.rowMultiSelectWithClick ? 'multiple' : 'single'"
    :rowMultiSelectWithClick="props.configaggrid.rowMultiSelectWithClick"
    :suppressColumnVirtualisation="props.configaggrid.isFlote" :get-row-style="props.configaggrid.rowStyle"
    @sortChanged="sortChanged">
  </AgGridVue>
  <div class="pagination-wrapper-aggrid">
    <!-- <span class="aggridNum"> {{ LineNumber || 0 }}行</span> -->
    <el-pagination :teleported="false" layout="total, sizes, prev, pager, next, jumper" :background="true"
      v-if="props.configaggrid.paginationShow" :total="pageData.total" @current-change="PageSize"
      @size-change="changeSize" style="justify-content: center; margin-top: 10px" :page-size="query.size"
      :current-page="query.page" :page-sizes="pagingList" />
  </div>

  <!-- <paginationCopys
      v-if="props.configaggrid.paginationShow"
      :total="pageData.total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="changeSize"
      style="justify-content: center; margin-top: 10px"
      :page-size="query.size"
      :current="query.page"
      :page-size-options="pagingList"
  /> -->
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, withDefaults, nextTick } from 'vue'
//表格
import { AgGridVue } from 'ag-grid-vue3'

//表格中文处理
import { localeText } from '@/api/aggridZw'

// 引入element提示
import { ElMessage, Message } from 'element-plus'

//引入封装post
import { post, get } from '@/api/http'

//分页列表
import { pagingList } from '@/api/paging'
//封装好的记忆表头的方法
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
//重构ag-grid全选逻辑
import useAgGridFilterSelector from '@/utils/aggridFilterAllSelect'
//为每行设置最小宽度
import setAggridMinwidths from '@/utils/setAggridMinWidth'
import emitter from '@/hooks/useEventBus'

// ts写法
interface AggridInf {
  url: string //接口路径
  queryData: any //接口参数
  column: any
  checkboxShow: boolean
  rowMultiSelectWithClick: boolean
  default: DefaulInf
  paginationShow: boolean
  invokeiIterface: boolean
  queryPage: Number
  isRowClickSelect: boolean
  bottomTotal: boolean
  bottomTotalConfig: any[]
  rowClickRequest: boolean
}

// ts写法
interface DefaulInf {
  sortable: boolean //可排序
  resizable: boolean //可拖动改变列宽
  filter: boolean //可过滤筛选
  editable: boolean //是否可编辑
  //flex: 1
}

const aggridFs = useAgGridFilterSelector()
const props = withDefaults(
  defineProps<{
    configaggrid: AggridInf | any
  }>(),
  {
    configaggrid: {
      url: '', //接口路径
      queryData: {}, //接口参数
      column: [], //列表
      checkboxShow: false, //是否有选择宽
      rowMultiSelectWithClick: false, //点击行是否多选
      paginationShow: true, //分页是否显示
      invokeiIterface: true, //是否调用接口
      queryPage: 10, //是否调用接口
      default: {
        sortable: true, //可排序
        resizable: true, //可拖动改变列宽
        filter: true, //可过滤筛选
        editable: false, //是否可编辑
        //flex: 1
        fileName: '', //文件名，用于记忆表头顺序
      },
      isRowClickSelect: false,
      noPageConfig: false, //不需要分页配置
      isFlote: false,
      selectable: undefined,
      bottomTotal: false,
      bottomTotalConfig: [],
      rowClickRequest: false,
    },
  }
)
const emit = defineEmits([
  'update:listData',
  'SelectionChanged',
  'change:rowSelected',
  'rowClickRequest',
])
const htmlElement = document.documentElement
// loading...
let loadingElplus = ref<boolean>(false)
// 表格准备事件
const gridOption = ref()
const colState = ref()

interface Pagein {
  dataList: any
  tc: any
  total: number
}

// 跟请求参数无关的放这里
let pageData = reactive<Pagein>({
  dataList: [], //数据
  tc: [], //column
  total: 0, //总条数
})
//getlist初始化接口参数
let query = reactive<any>({
  page: 1,
  size: props.configaggrid.queryPage ? props.configaggrid.queryPage : 10,
})
// 分页事件
const PageSize = (val: any) => {
  query.page = val
  getList()
}

const changeSize = (val: any) => {
  query.size = val
  query.page = 1
  getList()
}
// let checkbox = ref([
//   {
//     headerCheckboxSelection: true,
//     checkboxSelection: true,
//     width: 50,
//     showDisabledCheckboxes: false,
//   },
// ])
// if (props.configaggrid.checkboxShow) {
//   props.configaggetLisgrid.column = checkbox.value.concat(props.configaggrid.column)
//   console.log(props.configaggrid.column)
// }
//获取数据
const getList = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const { url, queryData, fileName, isGet, isLimit, noPageConfig } = props.configaggrid
      loadingElplus.value = true
      let res: any
      let tempQuery = JSON.parse(JSON.stringify(query))
      if (isLimit) {
        tempQuery.limit = tempQuery.size
        tempQuery.size = undefined
      }
      if (isGet) {
        res = await get({ url: url, data: { ...tempQuery, ...queryData } })
      } else {
        if (noPageConfig) {
          res = await post({ url: url, data: { ...queryData } })
        } else {
          res = await post({ url: url, data: { ...tempQuery, ...queryData } })
        }
      }

      if (res.code == 200) {
        if (res.data.list) {
          pageData.dataList = res.data.list
          if (props.configaggrid.bottomTotal) setTableTotalRow(res.data.list)
          emit('update:listData', res.data.list)
        } else if (res.data.data) {
          pageData.dataList = res.data.data
          if (props.configaggrid.bottomTotal) setTableTotalRow(res.data.data)
          emit('update:listData', res.data.data)
        } else if (res.data.items) {
          pageData.dataList = res.data.items
          if (props.configaggrid.bottomTotal) setTableTotalRow(res.data.items)
          emit('update:listData', res.data.items)
        } else {
          pageData.dataList = res.data
          if (props.configaggrid.bottomTotal) setTableTotalRow(res.data)
          emit('update:listData', res.data)
        }
        gridOption.value.setRowData(pageData.dataList)
        LineNumber.value = pageData.dataList.length || 0

        emitter.emit('lenghensssss', pageData.dataList.length)
        autoSizeAll()
        // updateGridState01()
        aggridFs.resetAgFs()

        if (res.data.items) {
          if (res.data.page) {
            pageData.total = res.data.page.total
          } else {
            pageData.total = res.data.total
          }
        } else {
          pageData.total = res.data.total
        }

        loadingElplus.value = false
        if (props.configaggrid.fileName) {
          // console.log('fileName', props.configaggrid.fileName)
          const result: any = await updateGridState01()
          // // console.log('result', result)
          // gridOption.value.setColumnDefs(setAggridMinwidths(result))
        }

        nextTick(() => {
          // 更新表头的最大行号
          let yourColumnDefs = gridOption.value.getColumnDefs()
          let rowIndexColumn = yourColumnDefs.find((colDef) => colDef.colId === 'ROW_INDECX')
          if (rowIndexColumn) {
            let maxNumberIndex = []
            gridOption.value.forEachNodeAfterFilter((row: any) => {
              maxNumberIndex.push(row)
            })
            rowIndexColumn.headerName = maxNumberIndex.length
            gridOption.value.setColumnDefs(yourColumnDefs)
          }
        })
        resolve('ok')
        return
      }
      ElMessage.error(res.message)
      reject('error')
    } finally {
      loadingElplus.value = false
    }
  })
}
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
  updateGridState01()
}
//添加行
const add = () => {
  // pageData.dataList.push({
  //   projectCode: 'ouihadpc',
  // })
  // gridOption.value.setRowData(pageData.dataList)
}
//删除行
// let onRemoveSelected = () => {
//   const selectedData = gridOption.value.getSelectedRows()
//   gridOption.value.applyTransaction({ remove: selectedData })
// }
/**
*aggrid小知识:
设置：rowMultiSelectWithClick="true"：允许通过单击选择多行
设置：rowSelection='single' 设置为启用单行选择。无法选择多行multiple:多选
设置：isRowSelectable=()=>{}里面写tru，false 设置行是否可选
设置：api.refreshCells() 如果做出操作没有反应，应该通知api去更改
设置： suppressCopyRowsToClipboard = true如果您想将行选择用于其他目的并希望复制焦点单元格而不是选定的行，您可以通过设置禁用复制行
}
* */
const isRowSelectable = (rowNode: any) => {
  if (props.configaggrid.selectable) {
    return props.configaggrid.selectable(rowNode)
  } else {
    return rowNode.data && rowNode.data.projectCode == 'ouihadpc' ? false : true
  }
}
//获取选中行
const getSelectedRows = () => {
  return gridOption.value.getSelectedRows()
}
const onCellClicked = (e: any) => {
  if (e.colDef.headerName == '操作') return
  emit('change:rowSelected', e)
}
const onRowClicked = (event: any) => {
  if (props.configaggrid.rowClickRequest) {
    emit('rowClickRequest', event)
  }
}
const onSelectionChanged = (params: any) => {
  console.log(params)

  if (params.source === 'uiSelectAll') {
    //点击的全选的选择框
    const allNode: any = []
    // 过滤后的值
    const selectedRowsID: any = []
    gridOption.value.forEachNodeAfterFilter((row: any) => {
      selectedRowsID.push(row.id)
    })

    gridOption.value.forEachNode((node: any) => {
      allNode.push(node)
    })
    if (allNode.length === gridOption.value.getSelectedRows().length) {
      //全选状态  （区分取消全选还是全选）
      allNode.forEach((item: any) => {
        var rowNode = gridOption.value.getRowNode(item.id) // 获取行节点
        let isSame = selectedRowsID.includes(item.id)
        if (isSame) {
          rowNode.setSelected(true) // 勾选行
        } else {
          rowNode.setSelected(false) // 不勾选行
        }
      })
    }
  }
}
const onFilterChanged = (params: any) => {
  gridOption.value.forEachNode((node: any) => {
    node.setSelected(false)
  })
}
// 设置接口参数
const setQuery = async (query1: any) => {
  query.page = 1
  props.configaggrid.queryData = query1
  await getList()
}
//获取选中选中行
const applyTransaction = (data: any) => {
  gridOption.value.applyTransaction(data)
  // pageData.dataList.map((item: any, i: number) => {
  //   if (data.remove[0].id == item.id) {
  //     console.log(pageData.dataList.splice(i, 1))
  //     // pageData.dataList = pageData.dataList.split(0, i)
  //   }
  // })
}
// 设置表格数据
const setdataListIterface = (data: any) => {
  pageData.dataList = data
  gridOption.value?.setRowData(data)
  emitter.emit('lenghensssss', pageData.dataList.length)
  LineNumber.value = pageData.dataList.length || 0
  aggridFs.resetAgFs()
  //  updateGridState01()
}
onMounted(async () => {
  if (props.configaggrid.invokeiIterface) {
    console.log('调用了getList')
    await getList()
  }
})
const getListData = () => {
  let allRowsData: any[] = []
  console.log('aaa', gridOption.value)
  gridOption.value.forEachNode((node: any) => {
    allRowsData.push(node.data)
  })
  //   gridOption.value.startEditingCell({
  //     rowIndex: 0,
  //     colKey:'stockInCode'
  // });
  return allRowsData
}
//单元格编辑事件
const startEditingCell = (index: Number, key: string) => {
  gridOption.value?.startEditingCell({
    rowIndex: index,
    colKey: key,
  })
}
//关闭单元格编辑事件
const stopEditing = () => {
  gridOption.value?.stopEditing()
}
//导出事件
const exportDataAsExcel = (name: string) => {
  gridOption.value?.exportDataAsExcel({
    fileName: `${name}.xlsx`,
    // fileName: 'myDataExport.xlsx',//文件名称
    // sheetName: 'CustomSheetName'//页签名称
  })
}
// 自动调整列宽
const autoSizeAll = () => {
  setTimeout(() => {
    try {
      if (colState && colState.value && colState.value.getColumns) {
        if (colState.value.getColumns().length == 0) return
        const allColumnIds = colState.value
          .getColumns()
          .map((column: { pinned: any; getId: () => any }) => {
            if (!column.pinned && column.getId()) {
              return column.getId()
            }
          })
        nextTick(() => {
          colState.value.autoSizeColumns(
            allColumnIds.filter((item: any) => item),
            false
          )
        })
      }
    } catch (error) {
      console.log(error)
    }
  }, 100)
}
//根据id 勾选行数据
const selectRowById = (idList: any) => {
  gridOption.value?.forEachNode((node: any) => {
    if (idList.includes(node.data.upkeepName)) {
      node.setSelected(true)
    }
  })
}
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
  saveOrUpdateGridState01(
    props.configaggrid.fileName,
    gridOption,
    colState,
    props.configaggrid.column
  )
const onColumnMoved = () => {
  saveGridState01()
}
const onColumnResized = () => {
  saveGridState01()
}
const onColumnVisible = () => {
  saveGridState01()
}
const AggridonClick = () => {
  // 获取当前正在编辑的单元格的信息
  const editingCells = gridOption.value?.getEditingCells()
  if (editingCells.length != 0) stopEditing()
}
const deselectAll = () => {
  gridOption.value?.deselectAll()
}
const LineNumber = ref()

const onFilterChangeds = (params: any) => {
  aggridFs.onFilterChanged(params)
  let dataList: any = []

  params.api.forEachNodeAfterFilter((row: any, index: number) => {
    dataList.push(row.data)
  })

  params.api.forEachNode((node, index) => {
    const rowIndex = index + 1
    if (node.data.ROW_INDECX !== rowIndex) {
      node.setDataValue('ROW_INDECX', rowIndex)
    }
  })

  let yourColumnDefs = gridOption.value.getColumnDefs()
  // 找到行号列的配置对象
  let rowIndexColumn = yourColumnDefs.find((colDef) => colDef.colId === 'ROW_INDECX')
  // 如果找到了行号列的配置对象，则更新其 headerValue 属性为最大的 ROW_INDEX
  if (rowIndexColumn) {
    rowIndexColumn.headerName = dataList.length
    gridOption.value.setColumnDefs(yourColumnDefs)
  }

  // LineNumber.value = dataList.length || 0

  emitter.emit('lenghensssss', dataList.length)
}

const sortChanged = (params) => {
  let dataList = []
  let maxRowIndex = 0

  // 遍历过滤后的节点，更新行号并收集数据
  params.api.forEachNodeAfterFilter((node, index) => {
    const rowIndex = index + 1
    if (node.data.ROW_INDECX !== rowIndex) {
      node.setDataValue('ROW_INDECX', rowIndex)
    }
    dataList.push(node.data)
    maxRowIndex = Math.max(maxRowIndex, rowIndex)
  })

  // 更新表头的最大行号
  let yourColumnDefs = gridOption.value.getColumnDefs()
  let rowIndexColumn = yourColumnDefs.find((colDef) => colDef.colId === 'ROW_INDECX')
  if (rowIndexColumn) {
    rowIndexColumn.headerName = maxRowIndex
    gridOption.value.setColumnDefs(yourColumnDefs)
  }
}

//导出事件新：支持导出勾选的行
const exportSelectedRows = (params: any) => {
  gridOption.value?.exportDataAsExcel({
    fileName: `${params.fileName}.xlsx`,
    onlySelected: params.onlySelected, // 只勾选导出的行数据
    // fileName: 'myDataExport.xlsx',//文件名称
    // sheetName: 'CustomSheetName'//页签名称
  })
}
// 重新绘制行
const redrawRows = () => {
  gridOption.value.redrawRows()
}
const selecetionChange = (p: any) => {
  aggridFs.clickAllSelectors(p)
  emit('SelectionChanged', p)
}
//自定义表格底部合并汇总
const setTableTotalRow = (data: any) => {
  console.log('sss')
  if (!props.configaggrid.bottomTotal) return
  const totalRowObj = {
    defaultCkBox: '汇总',
  }
  props.configaggrid.bottomTotalConfig.forEach((item: any) => {
    totalRowObj[item] = data.reduce((sum: any, cur: any) => {
      if (!cur[item] || isNaN(cur[item])) cur[item] = 0
      return Number(sum) + Number(cur[item])
    }, 0)
  })
  for (let key in totalRowObj) {
    if (key !== 'defaultCkBox') totalRowObj[key] = parseFloat(totalRowObj[key]).toFixed(2)
  }
  nextTick(() => {
    gridOption.value.setPinnedBottomRowData([totalRowObj])
  })
}
//获取所有表格节点
const forEachNode = (Callback: any) => {
  return gridOption.value.forEachNode(Callback)
}
// const test = () => {
//   return colState.value.getAllColumns()
// }
// 对外暴露的属性
defineExpose({
  getSelectedRows,
  setQuery,
  setdataListIterface,
  applyTransaction,
  getListData,
  exportDataAsExcel,
  startEditingCell,
  stopEditing,
  AggridonClick,
  autoSizeAll,
  deselectAll,
  selectRowById,
  exportSelectedRows,
  redrawRows,
  setTableTotalRow,
  forEachNode,
})
</script>
<script lang="ts">
export default defineComponent({
  name: 'encapsulationAgrid',
})
</script>
<style scoped>
/* html,
body {
width: 100%;
height: 100%;
} */
/* ag-header-group-cell-label */
/* div >>> .ag-header-group-cell-label { */
/* background-color: gold; */
/* color: red; */
/* justify-content: center;  */
/* } */
:deep(.ag-header-group-cell) {
  border-right: 1px #babfc7 solid;
}

:deep(.arco-trigger-popup) {
  z-index: 10000 !important;
}

.arco-trigger-popup {
  z-index: 10000 !important;
}

:deep(.arco-trigger-popup) {
  z-index: 10000 !important;
}

:deep(.ag-cell),
:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

.aggridNum {
  background-color: rgb(245, 221, 178);
  padding: 5px;
  margin-top: 10px;
}

.pagination-wrapper-aggrid {
  width: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* :deep(.ag-cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.ag-ltr .ag-selection-checkbox) {
  margin:0 2px !important;
} */
:deep(.ag-ltr .ag-selection-checkbox) {
  margin: 0 !important;
}
</style>
